package com.common.help.test13;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {

	/**
	 * 服务端  ServerSocketChannel  
	 * 客户端  SocketChannel
	 */
	private ServerSocketChannel server;
	private Selector selector;
	
	private ByteBuffer send = ByteBuffer.allocate(1024);
	private ByteBuffer recive = ByteBuffer.allocate(1024);
	
	public NIOServer(int port) throws IOException{
		//先修路
		server = ServerSocketChannel.open();
		//开个口子给进
		server.socket().bind(new InetSocketAddress(port));
		server.configureBlocking(false);//非阻塞
		//管家开始管理
		selector = Selector.open();
		
		server.register(selector, SelectionKey.OP_ACCEPT);//告诉管家准备进来
		
		System.out.println("NIO服务端已经准备就绪 服务端口:"+port);
	}
	public void listener() throws IOException{
		//轮询这些key
		while(true){
			//查看还有没有排队的客户
			int num = selector.select();
			if(0 == num){
				continue;
			}
			Set<SelectionKey> selections = selector.selectedKeys();
			Iterator<SelectionKey> iterator = selections.iterator();//边遍历边删除
				while(iterator.hasNext()){
					SelectionKey selectionKey = iterator.next();//拿到这个编号开始搞事情
					process(selectionKey);//执行
					iterator.remove();
				}
		}
	}
	private void process(SelectionKey selectionKey) throws IOException {
		
		if(selectionKey.isAcceptable()){//连接
			//知道是哪个客户端
			SocketChannel client = server.accept();
			client.configureBlocking(false);
			client.register(selector, SelectionKey.OP_READ);
		}else if(selectionKey.isReadable()){
			recive.clear();
			SocketChannel channel = (SocketChannel)selectionKey.channel(); 
			int len = channel.read(recive);
			if(len>0){
				System.out.println("消息为 ："+new String(recive.array(),0,len));
			}
		}else if(selectionKey.isWritable()){
			
		}
		
		
	}
	public static void main(String[] args) throws IOException {
		new NIOServer(8080).listener();;
	}
}
